<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 列表
 *
 * @author      Eden
 * @datetime    2016/12/9 00:43
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Bbslist_Model extends API_Model
{
    const PAGE_SIZE = 20;

    private $page = 1;

    /**
     * 参数
     * @var array
     */
    private $params = array();

    private $total = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主函数
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            $page = $this->input->get('page');
            $page = !empty($page) && $page > 0 ? intval($page) : 1;
            $offset = ($page - 1) * self::PAGE_SIZE;

            $result = $this->_getBbsLists($offset, self::PAGE_SIZE);
            $ret = array(
                'total' => 0,
                'data' => [],
                'nextPage' => false
            );
            if ($result) {
                $ret = array(
                    'total' => intval($this->total),
                    'data' => $result,
                    'nextPage' => $this->total > ($offset + self::PAGE_SIZE)
                );
            }
            $send['state'] = true;
            $send['data'] = $ret;
        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取 BBS 列表
     * @param int $offset
     * @param int $pageSize
     * @return bool
     */
    protected function _getBbsLists($offset = 0, $pageSize = 20)
    {
        $db = clone($this->db);
        $where = array(
            'status' => 1
        );
        $db->where($where);
        $this->total = $db->count_all_results('bbs');

        if (empty($this->total)) {
            return false;
        }

        $bbsDb = clone($this->db);
        $query = $bbsDb->where($where)
            ->select('b.id, b.userId, b.content, b.likes, b.comments, b.created, b.source, ba.attachment')
            ->from('bbs as b')
            ->limit($pageSize, $offset)
            ->join('bbs_attachment as ba', 'ba.bbsId = b.id')
            ->order_by('b.created', 'DESC')
            ->get();

        $bbsRows = $query->result_array();
        if (empty($bbsRows)) {
            return false;
        }

        $userIds = $bbsIds = array();
        if (is_array($bbsRows)) foreach ($bbsRows as &$row) {
            $userId = $row['userId'];
            array_push($userIds, $userId);
            array_push($bbsIds, $row['id']);
            $row['bbsId'] = intval($row['id']);
            $row['userId'] = intval($userId);
            $row['likes'] = intval($row['likes']);
            $row['comments'] = intval($row['comments']);
            $row['created'] = formateTimeStamp($row['created']);
            $row['isLike'] = false;
            $row['attachment'] = bbsThumb($row['attachment'], $this->params['type']);
        }

        $thumbUpInfo = $this->_getThumbupInfo($bbsIds);
        $thumbUpInfo = !$thumbUpInfo ? [] : $thumbUpInfo;
        $userInfos = $this->_getUserInfo($userIds);
        $bbsConfig = $this->_getBbsConfig();
        foreach ($bbsRows as &$bbs) {
            $bbsUserId = $bbs['userId'];
            if ($bbs['source'] == 'admin' && !empty($bbsConfig)) {
                $user = ['avatar' => thumb($bbsConfig['thumb'], 100, 100), 'nickName' => $bbsConfig['nickname']];
            } else {
                $user = !empty($userInfos[$bbsUserId]) ? $userInfos[$bbsUserId] : ['avatar' => '', 'nickName' => ''];
            }
            $bbs = array_merge($bbs, $user);
            $bbs['isLike'] = in_array($bbs['bbsId'], $thumbUpInfo) ? true : false;
            unset($bbs['id']);
        }
        return $bbsRows;
    }

    /**
     * 获取设置
     * @return mixed
     */
    private function _getBbsConfig()
    {
        $this->load->model('common/Setting_Model', 'sets');
        return $this->sets->getSetting('system', 'bbs');
    }

    /**
     * 是否点赞
     * @param $bbsIds
     * @return bool
     */
    public function _getThumbupInfo($bbsIds)
    {
        if (empty($this->params['userId'])) {
            return false;
        }

        $db = clone($this->db);
        $db->where('userId', $this->params['userId']);
        $db->where_in('bbsId', $bbsIds);
        $q = $db->get('bbs_likes');
        $rows = $q->result_array();
        if (empty($rows)) {
            return false;
        }

        $likes = [];
        foreach($rows as $row) {
            $likes[] = $row['bbsId'];
        }
        return $likes;
    }

    /**
     * 获取用户数据
     * @param array $userIds
     * @return array
     */
    protected function _getUserInfo($userIds = array())
    {
        $query = $this->db->select('u.id, u.nickName, up.avatar')
            ->from('user as u')
            ->join('user_profile as up', 'up.userId = u.id')
            ->where_in('u.id', $userIds)
            ->get();
        $rows = $query->result_array();
        $users = array();
        if ($rows && is_array($rows)) foreach ($rows as $row) {
            $userId = $row['id'];
            $info = array();
            $info['avatar'] = thumb($row['avatar'], 100, 100);
            $info['nickName'] = $row['nickName'];
            $users[$userId] = $info;
        }
        return $users;
    }
}
